import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import _ from 'loadsh'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { TitleLine, TextLine, TextCell, Split } from '@components/ApprovePre/Approve'

class StepOneHistory extends Component {
  state = {
    keyTitleMap: {}
  }

  // 格式化日期
  formatDate (date) {
    if (date) {
      return moment(date * 1000).format('YYYY-MM-DD HH:mm')
    }
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.action || {}, 'vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  // 根据key获取标题
  getTitleByKey (key) {
    const { keyTitleMap } = this.state
    return keyTitleMap[key]
  }

  // 获取值
  getValueByKey (key, nullValue = '无', unit) {
    const { action } = this.props
    const { varsMap } = action
    let v = (varsMap[key] || {}).value
    if (v && typeof v === 'string' && unit) {
      v = v + unit
    }
    return v || nullValue
  }

  // 格式化时间戳为时间字符串
  formatValueToTime (n) {
    if (n) {
      return moment(n * 1000).format('YYYY-MM-DD')
    }
    return '无'
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
    }
  }

  componentDidMount () {
    this.initKeyTitleMap()
  }

  render () {
    const { action } = this.props
    const t = this.getTitleByKey.bind(this)
    const v = this.getValueByKey.bind(this)
    return (
      <div>
        <TitleLine title={this.props.action.step_name} operator={action.operator} time={this.formatDate(action.complete_datetime)} />
        <TextLine>
          <TextCell>{t('limitextended_days')}：{v('limitextended_days', '无', '天')}</TextCell>
          <Split />
          <TextCell>{t('limitextended_end_datetime')}：{this.formatValueToTime(v('limitextended_end_datetime', false))}</TextCell>
        </TextLine>
        <TextLine>
          <TextCell style={{ width: '65%' }}>{action.remark_alias || '备注'}：{action.remark || '无'}</TextCell>
        </TextLine>
        {this.props.renderDocument()}
      </div>
    )
  }
}

StepOneHistory.proptypes = {
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  action: PropTypes.object,
  renderDocument: PropTypes.func
}

StepOneHistory.defaultProps = {
  userInfo: {},
  instance: {},
  action: {},
  renderDocument: () => { }
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(StepOneHistory)
